import React, { useEffect } from 'react';
import { connect } from 'dva';
import { Form, FormItem, createFormActions, FormEffectHooks } from '@formily/antd';
import { NumberPicker, Radio, Switch, Input } from '@formily/antd-components';
import classNames from 'classnames';
import throttle from 'lodash/throttle';
import has from 'lodash/has';
import get from 'lodash/get';
import styles from '../../styles.less';

const actions = createFormActions();
const { onFormInputChange$ } = FormEffectHooks;

function ForStaticText({ dispatch, current }) {
  useEffect(() => {
    // 清空状态
    actions.reset({ validate: false });

    // 剔除holder是冗余的key
    const keys = Object.keys(actions.getFormGraph()).filter(val => val !== '');

    // 遍历，给所有的formItem设置值
    keys.forEach(value => {
      if (has(current, value)) {
        actions.setFieldValue([value], get(current, value));
      }
    });
  }, [current]);

  return (
    <Form
      className={classNames(styles.configForm)}
      actions={actions}
      colon={false}
      effects={() => {
        // 只监控人工操作引起的FormItem值变化
        onFormInputChange$().subscribe(
          throttle(
            async () => {
              await actions.validate({ silent: true });
              // actions.getFormState().valid取到的结果是异步的，所以必须用到await actions.validate才能得到精确的结果
              const isValid = actions.getFormState().valid;

              // 校验失败
              if (!isValid) {
                return;
              }

              dispatch({
                type: 'formDesigner/updateNode',
                payload: actions.getFormState().values,
              });
            },
            300,
            { trailing: true, leading: false }
          )
        );
      }}
    >
      <FormItem
        label="字号"
        name="fontSize"
        triggerType="onChange"
        component={NumberPicker}
        formatter={value => `${value} px`}
        parser={value => value.replace(' px', '')}
        initialValue="13"
        min={13}
      />

      <FormItem
        label="对齐方式"
        name="textAlign"
        triggerType="onChange"
        component={Radio.Group}
        dataSource={[
          { label: '左', value: 'left' },
          { label: '中', value: 'center' },
          { label: '右', value: 'right' },
        ]}
        initialValue="left"
      />

      <FormItem
        label="加粗"
        name="bold"
        triggerType="onChange"
        component={Switch}
        initialValue={false}
      />

      <FormItem
        label="内容"
        name="content"
        triggerType="onChange"
        component={Input.TextArea}
        placeholder="请输入"
        autoSize={{ minRows: 4 }}
      />
    </Form>
  );
}

export default connect(({ formDesigner }) => ({
  current: formDesigner.current,
}))(ForStaticText);
